﻿using System;
using System.Threading.Tasks;
using SqlSugar;
using Ioacp.Library.Helpers;
using Ioacp.Syka.Dbs;

namespace Ioacp.Syka
{
    /// <summary>
    /// 思源科安 SDK
    /// </summary>
    public class SykaSDK
    {
        #region SetConnString

        private string _connString = string.Empty;

        /// <summary>
        /// 设置连接字符串
        /// </summary>
        /// <param name="connString"></param>
        public void SetConnString(string connString)
        {
            _connString = connString;
        }

        #endregion

        /// <summary>
        /// 设备 SN
        /// </summary>
        public string DeviceSN { get; set; }

        /// <summary>
        /// 是否运行
        /// </summary>
        public bool IsRuning { get; set; }

        /// <summary>
        /// 人证识别事件
        /// </summary>
        public event EventHandler<dynamic> OnFaceCardDetectionChanged;

        #region Start

        private Task _task;

        /// <summary>
        /// 开始运行
        /// </summary>
        public void Start()
        {
            // 标记开始运行
            IsRuning = true;

            // 清空表, 防止对后续数据有影响
            UniqueDetectInfo_Truncate();

            // 开启新任务
            _task = Task.Run(() =>
            {
                while (IsRuning)
                {
                    WaitData();

                    _task.Wait(100);
                }
            });
        }

        #endregion

        #region WaitData

        /// <summary>
        /// 等待数据
        /// </summary>
        private void WaitData()
        {
            dynamic result = UniqueDetect_LastItem(DeviceSN);

            // 有数据发出通知
            if (result != null)
            {
                // 人脸卡侦测时间
                OnFaceCardDetectionChanged?.Invoke(this, (result as UniqueDetectInfo).WorkerSN);

                // 删除数据
                Item_Delete(result);
            }
        }

        #endregion

        private DateTime _lastErrorTime = DateTime.MinValue;

        #region UniqueDetect_LastItem

        /// <summary>
        /// 最后一条检测记录
        /// </summary>
        /// <returns></returns>
        public dynamic UniqueDetect_LastItem(string deviceSN)
        {
            try
            {
                var result = SqlInstance.Queryable<UniqueDetectInfo>().Where(t => t.DeviceSN == deviceSN).OrderBy("ID Desc").Take(1).ToList();

                if (result.Count > 0)
                    return result[0];
                else
                    return null;
            }
            catch(Exception ex)
            {
                if ((DateTime.Now - _lastErrorTime).TotalMinutes >1)
                {
                    LogEx.SqlError(ex);
                    _lastErrorTime = DateTime.Now;
                }
                return null;
            }
        }

        #endregion

        #region UniqueDetectInfo_Truncate

        /// <summary>
        /// 清除之前的记录
        /// </summary>
        public void UniqueDetectInfo_Truncate()
        {
            try
            {
                SqlInstance.Ado.ExecuteCommand("Truncate Table Raw_Recognize_Record");
            }
            catch (Exception ex)
            {
                LogEx.SqlError(ex);
            }
        }

        #endregion

        #region WorkType_List

        /// <summary>
        /// 列出部门信息
        /// </summary>
        /// <returns></returns>
        public dynamic WorkType_List()
        {
            try
            {
                return SqlInstance.Queryable<WorkTypeInfo>().ToList();
            }
            catch (Exception ex)
            {
                LogEx.SqlError(ex);
                return null;
            }
        }

        #endregion

        #region Duty_List

        /// <summary>
        /// 列出职务信息
        /// </summary>
        public dynamic Duty_List()
        {
            try
            {
                return SqlInstance.Queryable<DutyInfo>().ToList();
            }
            catch (Exception ex)
            {
                LogEx.SqlError(ex);
                return null;
            }
        }

        #endregion

        #region Dept_List

        /// <summary>
        /// 列出部门信息
        /// </summary>
        /// <returns></returns>
        public dynamic Dept_List()
        {
            try
            {
                return SqlInstance.Queryable<DeptInfo>().ToList();
            }
            catch (Exception ex)
            {
                LogEx.SqlError(ex);
                return null;
            }
        }

        #endregion

        #region Staff_List

        /// <summary>
        /// 列出员工信息
        /// </summary>
        /// <returns></returns>
        public dynamic Staff_List()
        {
            try
            {
                return SqlInstance.Queryable<StaffInfo>().ToList();
            }
            catch (Exception ex)
            {
                LogEx.SqlError(ex);
                return null;
            }
        }

        #endregion

        #region Item_Delete

        /// <summary>
        /// 数据删除
        /// </summary>
        /// <param name="item"></param>
        public void Item_Delete(dynamic item)
        {
            try
            {
                SqlInstance.Deleteable(item).ExecuteCommand();
            }
            catch (Exception ex)
            {
                LogEx.SqlError(ex);
            }
        }

        #endregion

        #region Dom_Save

        /// <summary>
        /// 保存职务信息
        /// </summary>
        /// <param name="result"></param>
        public void Dom_Save(dynamic result)
        {
            try
            {
                if (result == null) return;

                if (result.Inserts.Count > 0)
                    SqlInstance.Insertable(result.Inserts).ExecuteCommand();

                if (result.Updates.Count > 0)
                    SqlInstance.Updateable(result.Updates).ExecuteCommand();

                if (result.Deletes.Count > 0)
                    SqlInstance.Updateable(result.Deletes).ExecuteCommand();
            }
            catch(Exception ex)
            {
                LogEx.SqlError(ex);
            }
        }

        #endregion

        #region SqlInstance

        /// <summary>
        /// 实例
        /// </summary>
        public SqlSugarClient SqlInstance
        {
            get
            {
                var db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = _connString,  // 必填, 数据库连接字符串
                    DbType = DbType.MySql,      // 必填, 数据库类型
                    IsAutoCloseConnection = true,   // 默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                    InitKeyType = InitKeyType.Attribute    // 默认SystemTable, 字段信息读取, 如：该属性是不是主键，是不是标识列等等信息
                });

                //用来打印Sql方便你调式    
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                };

                return db;
            }
        }

        #endregion
    }
}